﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Data;
using App.Core.Extensions;
using System.IO;

public partial class Pages_Private_SpecialOfferChange : BasePage
{
    private int _ID = 0;
    private bool _IsEditMode = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindDropDownLists();            
            BindSpecialOfferInfo();
            ShowSuccessMessage();
            //btnList.Visible = base.IsAdministrator;
            chkHasPublished.Enabled = base.IsAdministrator;
        }
    }
    /// <summary>
    /// Bindis the Page Initialization Variables
    /// </summary>
    protected void BindPageInfo()
    {
        _ID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
        //if (_ID > 0 && base.IsAdministrator)
        if (_ID > 0)
        {
            _IsEditMode = true;
            h4Heading.InnerHtml = "Edit Special Offer";
        }
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }

    /// <summary>
    /// Binds Dropdownlists for the initial request.
    /// </summary>
    protected void BindDropDownLists()
    {
        ///If the Logged In user is an Individual
        if (SessionCache.CurrentUser.GroupID == ConfigReader.IndividualUserGroupID)
        {
            BindDropdownList.RentTypes(ddlProjectType);
            rfvProjectType.ErrorMessage = "Please Select a Type of Rent";
            lblProjectType.Text = "Type of Rent";
        }
        else
            BindDropdownList.PropertyTypes(ddlProjectType, true);

        BindDropdownList.Cities(ddlCity, ConfigReader.CountryIDOfBangladesh);
    }
    protected void ShowSuccessMessage()
    {
        if(String.Compare(WebUtil.GetQueryStringInString(AppConstants.QueryString.SUCCESS_MESSAGE), "True", false) == 0)
            WebUtil.ShowMessageBox(divMessage, "Your Special Offer Submitted Successfully.", false);
    }
    /// <summary>
    /// Binds SpecialOffer Info Requested through Query Strings
    /// </summary>
    protected void BindSpecialOfferInfo()
    {
        //if (_IsEditMode && base.IsAdministrator)
        if (_IsEditMode)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            SpecialOffer entity = context.SpecialOffers.FirstOrDefault(P => P.ID == _ID);//dao.GetByID(_ID);
            if (entity == null)
                ShowErrorMessage();
            else
            {
                txtTitle.Text = entity.Title;
                txtDescription.Text = entity.Description;
                chkHasPublished.Checked = entity.HasPublished;
                if(entity.ZoneID.HasValue)
                {
                    ddlCity.SetSelectedItem(entity.Zone.CityID.ToString());
                    ddlCity_SelectedIndexChanged(ddlCity, EventArgs.Empty);
                    ddlZone.SetSelectedItem(entity.ZoneID.GetValueOrDefault().ToString());
                }
                ddlProjectType.SetSelectedItem(entity.ProjectType.GetValueOrDefault().ToString());
                ///Bind the Images
                if (!entity.PictureThumb.IsNullOrEmpty())
                {
                    divSpecialOfferPreviewContainer.InnerHtml = String.Format("<img class='EventImage' src='{0}/{1}' alt='' title='' />", AppConstants.SPECIAL_OFFER_IMAGES, entity.PictureThumb);
                    divSpecialOfferPreviewContainer.Visible = true;
                }
            }
        }
        else
            chkHasPublished.Checked = true;
    }
    /// <summary>
    /// Shows a Message in the UI and Hides the Data Editing Controls
    /// </summary>
    protected void ShowErrorMessage()
    {
        pnlFormContainer.Visible = false;
        WebUtil.ShowMessageBox(divMessage, "Requested Special Offer was not found.", true);
    }
    protected void SaveSpecialOffer()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        SpecialOffer entity = null;

        if (_IsEditMode)
            entity = context.SpecialOffers.FirstOrDefault(P => P.ID == _ID); //dao.GetByID(_ID);        
        else
        {
            entity = new SpecialOffer();
            entity.CustomerID = SessionCache.CurrentUser.CustomerID;
            entity.Created = DateTime.Now;
            context.AddToSpecialOffers(entity);
        }
        entity.Title = txtTitle.Text;
        entity.Description = txtDescription.Text;
        entity.ZoneID = ddlZone.SelectedValue.ToInt();
        entity.ProjectType = ddlProjectType.SelectedValue.ToInt();
        entity.HasPublished = chkHasPublished.Checked;        
        entity.Modified = DateTime.Now;
        entity.ModifiedBy = SessionCache.CurrentUser.ID;

        context.SaveChanges();

        ///Save the Picture
        if (fuPicture.HasFile)
        {
            String filePath = Server.MapPath(AppConstants.SPECIAL_OFFER_IMAGES);
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            ///Delete Existing Picture
            if (_IsEditMode && !entity.Picture.IsNullOrEmpty())
            {
                String file = Path.Combine(filePath, entity.Picture);
                if (File.Exists(file))
                    File.Delete(file);
            }
            ///Delete Existing Thumbnail
            if (!entity.PictureThumb.IsNullOrEmpty())
            {
                String fileThumb = Path.Combine(filePath, entity.PictureThumb);
                if (File.Exists(fileThumb))
                    File.Delete(fileThumb);
            }
            ///Save the File in Local Directory
            //String fileName = String.Format("{0}_{1}", entity.ID, Path.GetFileName(fuPicture.FileName));
            //fuPicture.SaveAs(Path.Combine(filePath, fileName));
            String outputFileName = Path.Combine(filePath, String.Format("{0}_{1}_Thumb{2}", entity.ID, Path.GetFileNameWithoutExtension(fuPicture.PostedFile.FileName), Path.GetExtension(fuPicture.PostedFile.FileName)));
            String inputFileName = Path.Combine(filePath, String.Format("{0}_{1}", entity.ID, Path.GetFileName(fuPicture.PostedFile.FileName)));
            fuPicture.SaveAs(inputFileName);
            WebUtil.GenerateThumbnail(inputFileName, outputFileName, ConfigReader.EventThumbWidth, false);

            entity.Picture = Path.GetFileName(inputFileName);
            entity.PictureThumb = Path.GetFileName(outputFileName);
            context.SaveChanges();
        }

        String url = String.Format("{0}?{1}={2}&{3}=True"
            , Request.Url.AbsolutePath
            , AppConstants.QueryString.ID, entity.ID 
            , AppConstants.QueryString.SUCCESS_MESSAGE);
        Response.Redirect(url);
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (fuPicture.HasFile && !WebUtil.IsValidImageFile(fuPicture.PostedFile))
            {
                WebUtil.ShowMessageBox(divMessage, "Please select a valid image file for Picture.", true);
                return;
            }  
            SaveSpecialOffer();
            //Response.Redirect(AppConstants.Pages.SPECIALOFFER_LIST);
            return;
        }
    }
    protected void btnList_Click(object sender, EventArgs e)
    {
        if (base.IsAdministrator)
            Response.Redirect(AppConstants.Pages.SPECIALOFFER_LIST_ADMIN);
        else
            Response.Redirect(AppConstants.Pages.SPECIALOFFER_LIST_COMPANY);
        return;
    }

    protected void cvImageFile_OnServerValidate(object sender, ServerValidateEventArgs e)
    {
        if (fuPicture.HasFile)
        {
            if (WebUtil.IsValidImageFile(fuPicture.PostedFile))
                e.IsValid = true;
            else
                e.IsValid = false;
        }        
    }
    protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindDropdownList.Zones(ddlZone, ddlCity.SelectedValue.ToInt());
    }
}